package com.baitiaojun.user.api.impl;

import com.alibaba.fastjson.JSONObject;
import com.baitiaojun.api.annotation.JSR303Verify;
import com.baitiaojun.api.domain.user.User;
import com.baitiaojun.api.util.RSAUtil;
import com.baitiaojun.api.vo.JsonRes;
import com.baitiaojun.user.api.SystemApi;
import com.baitiaojun.user.service.SystemService;
import com.baitiaojun.user.support.UserSupport;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Map;

/**
 * @类名 SystemConstoller
 * @作者 白条君
 * @创建日期 2022/11/1 01:27
 * @版本 1.0
 */
@RestController
public class SystemApiImpl implements SystemApi {

    @Resource
    private SystemService systemService;

    @Resource
    private UserSupport userSupport;

    @Resource
    private HttpServletResponse response;

    @Resource
    private HttpServletRequest request;

    @Override
    public JsonRes getRSAPublicKey() {
        String publicKeyStr = RSAUtil.getPublicKeyStr();
        return JsonRes.builder().data(publicKeyStr);
    }

    @JSR303Verify
    @Override
    public JsonRes register(@Valid User user, BindingResult result) throws Exception {
        systemService.register(user);
        return JsonRes.builder().success();
    }

    @JSR303Verify
    @Override
    public JsonRes login(@Valid User user, BindingResult result) throws Exception {
        String accessToken = systemService.login(user);
        response.addHeader("Authorization", accessToken);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        return JsonRes.builder().success();
    }

    @Override
    public JsonRes cancellation() {
        String token = userSupport.getToken(request);
        Map<String, Object> map = JSONObject.parseObject(JSONObject.toJSONString(userSupport.getCurrentUser(request)));
        systemService.cancellation(token, (String) map.get("phone"));
        return JsonRes.builder().success();
    }
}
